package com.lotus.lqmp.service.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lotus.idaas.sdk.common.UserInfoContext;
import com.lotus.lqmp.base.biz.bean.PageQuery;
import com.lotus.lqmp.base.third.model.CommonUserDTO;
import com.lotus.lqmp.service.common.enums.JrReviewStatusEnum;
import com.lotus.lqmp.service.common.enums.YesNoEnum;
import com.lotus.lqmp.service.common.utils.CommonUtil;
import com.lotus.lqmp.service.common.utils.UuidUtil;
import com.lotus.lqmp.service.controller.vo.req.ReviewPlanEcuMasterDataQueryReq;
import com.lotus.lqmp.service.controller.vo.resp.ReviewPlanEcuMasterDataResp;
import com.lotus.lqmp.service.dao.ReviewPlanEcuMasterDataMapper;
import com.lotus.lqmp.service.dao.entity.ReviewPlanEcuMasterDataDo;
import com.lotus.lqmp.service.service.ReviewPlanEcuMasterDataService;
import com.lotus.lqmp.service.service.UserInfoTransferService;
import com.lotus.lqmp.service.service.entity.ReviewPlanEcuMasterDataDto;
import com.lotus.lqmp.service.service.entity.ReviewPlanEcuMasterDataExportDto;
import com.lotus.platform.common.biz.impl.BaseBiz;
import com.lotus.platform.common.model.enums.DeletedStatusEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 评审记录ECU主数据Service业务层处理
 *
 * @author Shiheng.Liu1
 * @date 2022-03-29
 */
@Service
public class ReviewPlanEcuMasterDataServiceImpl extends BaseBiz<ReviewPlanEcuMasterDataMapper, ReviewPlanEcuMasterDataDo>
        implements ReviewPlanEcuMasterDataService{

    @Autowired
    private ReviewPlanEcuMasterDataMapper reviewPlanEcuMasterDataMapper;

    public static final String EXPORT_EXCEL_TEMPLATE_FILE_PATH = "/excelTemplate/reviewPlanMasterDataTemplate.xlsx";

    public static final String EXPORT_FILE_NAME = "评审计划Overall";

    public static final String EXPORT_FILE_USER_FORMAT = "%s<%s>";

    @Override
    public List<ReviewPlanEcuMasterDataDo> getByReviewPlanIds(List<Long> ids) {
        QueryWrapper<ReviewPlanEcuMasterDataDo> queryWrapper = new QueryWrapper(ids);
        queryWrapper.eq("deleted_status", String.valueOf(DeletedStatusEnum.normal.getCode()));
        queryWrapper.in("review_plan_id", ids);
        return reviewPlanEcuMasterDataMapper.selectList(queryWrapper);
    }

    @Autowired
    private UserInfoTransferService userInfoTransferService;

    @Override
    public Page<ReviewPlanEcuMasterDataResp> queryDriveLogList(
        PageQuery<ReviewPlanEcuMasterDataQueryReq> reviewPlanEcuMasterDataQueryReq) {
        ReviewPlanEcuMasterDataQueryReq queryInfo = reviewPlanEcuMasterDataQueryReq.getQueryInfo();
        long pageNum = reviewPlanEcuMasterDataQueryReq.getPageNum();
        long pageSize = reviewPlanEcuMasterDataQueryReq.getPageSize();
        long startIndex = (pageNum - 1) * pageSize;
        List<ReviewPlanEcuMasterDataDto> planEcuMasterDataDtos = reviewPlanEcuMasterDataMapper.queryMasterDataList(queryInfo, startIndex,
            pageSize);

        Integer total = reviewPlanEcuMasterDataMapper.countMasterData(queryInfo);
        Page<ReviewPlanEcuMasterDataResp> resultPage = new Page<>();
        resultPage.setSize(pageSize);
        resultPage.setCurrent(pageNum);
        resultPage.setTotal(total);
        // 获取用户信息
        List<String> userEmployeeNos = getUserEmployeeNos(planEcuMasterDataDtos);
        //Map<String, CommonUserDTO> userInfoByEmployeeNos = userInfoTransferService.getUserInfoByEmployeeNos(
        //    userEmployeeNos);

        Map<String, CommonUserDTO> userInfoByEmployeeNos = CollectionUtils.newHashMap();

        // dto转为vo
        List<ReviewPlanEcuMasterDataResp> reviewPlanEcuMasterDataResps = planEcuMasterDataDtos.stream().map(e -> {
            ReviewPlanEcuMasterDataResp vo = new ReviewPlanEcuMasterDataResp();
            BeanUtils.copyProperties(e, vo);
            transferForVo(e, vo, userInfoByEmployeeNos);
            return vo;
        }).collect(Collectors.toList());
        resultPage.setRecords(reviewPlanEcuMasterDataResps);

        return resultPage;
    }

    @Override
    public void handleExportIssueRecords(HttpServletResponse response, ReviewPlanEcuMasterDataQueryReq reviewPlanEcuMasterDataQueryReq)
        throws IOException {
        List<ReviewPlanEcuMasterDataDto> reviewPlanEcuMasterDataDtos
            = reviewPlanEcuMasterDataMapper.queryMasterDataList(reviewPlanEcuMasterDataQueryReq, null, null);
        // 获取用户信息
        List<String> userEmployeeNos = getUserEmployeeNos(reviewPlanEcuMasterDataDtos);
        //Map<String, CommonUserDTO> userInfoByEmployeeNos = userInfoTransferService.getUserInfoByEmployeeNos(
        //    userEmployeeNos);
        Map<String, CommonUserDTO> userInfoByEmployeeNos = CollectionUtils.newHashMap();

        List<ReviewPlanEcuMasterDataExportDto> exportDtos = reviewPlanEcuMasterDataDtos.stream().map(e -> {
            ReviewPlanEcuMasterDataExportDto exportDto = new ReviewPlanEcuMasterDataExportDto();
            BeanUtils.copyProperties(e, exportDto);
            transferForExportDto(e, exportDto, userInfoByEmployeeNos);
            return exportDto;
        }).collect(Collectors.toList());

        if (exportDtos.size() > 0) {
            CommonUtil.setResponseExportParam(response, URLEncoder.encode(EXPORT_FILE_NAME, "UTF-8"));
            InputStream templateFileIs = this.getClass().getResourceAsStream(EXPORT_EXCEL_TEMPLATE_FILE_PATH);
            EasyExcel.write(response.getOutputStream()).withTemplate(templateFileIs).sheet().doFill(exportDtos);
        }
    }

    private void transferForExportDto(ReviewPlanEcuMasterDataDto originalDto, ReviewPlanEcuMasterDataExportDto exportDto,
        Map<String, CommonUserDTO> userInfoByEmployeeNos) {
        if (originalDto.getSwdl() != null) {
            exportDto.setSwdl(YesNoEnum.enumFromKey(originalDto.getSwdl()).getValue());
        }
        if (originalDto.getObdRelated() != null) {
            exportDto.setObdRelated(YesNoEnum.enumFromKey(originalDto.getObdRelated()).getValue());
        }
        if (originalDto.getCyberSecurity() != null) {
            exportDto.setCyberSecurity(YesNoEnum.enumFromKey(originalDto.getCyberSecurity()).getValue());
        }
        if (originalDto.getNominated() != null) {
            exportDto.setNominated(YesNoEnum.enumFromKey(originalDto.getNominated()).getValue());
        }
        if (originalDto.getJr1ReviewStatus() != null) {
            exportDto.setJr1ReviewStatus(JrReviewStatusEnum.enumFromKey(originalDto.getJr1ReviewStatus()).getValue());
        }
        if (originalDto.getJr2ReviewStatus() != null) {
            exportDto.setJr2ReviewStatus(JrReviewStatusEnum.enumFromKey(originalDto.getJr2ReviewStatus()).getValue());
        }
        if (originalDto.getJr3ReviewStatus() != null) {
            exportDto.setJr3ReviewStatus(JrReviewStatusEnum.enumFromKey(originalDto.getJr3ReviewStatus()).getValue());
        }
        if (originalDto.getJr4ReviewStatus() != null) {
            exportDto.setJr4ReviewStatus(JrReviewStatusEnum.enumFromKey(originalDto.getJr4ReviewStatus()).getValue());
        }

        if (userInfoByEmployeeNos.get(originalDto.getGriEcuOwner()) != null) {
            CommonUserDTO commonUserDTO = userInfoByEmployeeNos.get(originalDto.getGriEcuOwner());
            exportDto.setGriEcuOwner(String.format(EXPORT_FILE_USER_FORMAT, commonUserDTO.getName(), commonUserDTO.getEmail()));
        }
        if (userInfoByEmployeeNos.get(originalDto.getUpl()) != null) {
            CommonUserDTO commonUserDTO = userInfoByEmployeeNos.get(originalDto.getUpl());
            exportDto.setUpl(String.format(EXPORT_FILE_USER_FORMAT, commonUserDTO.getName(), commonUserDTO.getEmail()));
        }
        if (userInfoByEmployeeNos.get(originalDto.getInterfacePerson()) != null) {
            CommonUserDTO commonUserDTO = userInfoByEmployeeNos.get(originalDto.getInterfacePerson());
            exportDto.setInterfacePerson(String.format(EXPORT_FILE_USER_FORMAT, commonUserDTO.getName(), commonUserDTO.getEmail()));
        }
        if (userInfoByEmployeeNos.get(originalDto.getEcuOwner()) != null) {
            CommonUserDTO commonUserDTO = userInfoByEmployeeNos.get(originalDto.getEcuOwner());
            exportDto.setEcuOwner(String.format(EXPORT_FILE_USER_FORMAT, commonUserDTO.getName(), commonUserDTO.getEmail()));
        }
        if (userInfoByEmployeeNos.get(originalDto.getSwqaEngineer()) != null) {
            CommonUserDTO commonUserDTO = userInfoByEmployeeNos.get(originalDto.getSwqaEngineer());
            exportDto.setSwqaEngineer(String.format(EXPORT_FILE_USER_FORMAT, commonUserDTO.getName(), commonUserDTO.getEmail()));
        }
    }

    private List<String> getUserEmployeeNos(List<ReviewPlanEcuMasterDataDto> planEcuMasterDataDtos) {
        Set<String> userEmployeeNos = new HashSet<>();
        for (ReviewPlanEcuMasterDataDto planEcuMasterDataDto : planEcuMasterDataDtos) {
            if (StringUtils.isNotBlank(planEcuMasterDataDto.getGriEcuOwner())) {
                userEmployeeNos.add(planEcuMasterDataDto.getGriEcuOwner());
            }
            if (StringUtils.isNotBlank(planEcuMasterDataDto.getUpl())) {
                userEmployeeNos.add(planEcuMasterDataDto.getUpl());
            }
            if (StringUtils.isNotBlank(planEcuMasterDataDto.getInterfacePerson())) {
                userEmployeeNos.add(planEcuMasterDataDto.getInterfacePerson());
            }
            if (StringUtils.isNotBlank(planEcuMasterDataDto.getEcuOwner())) {
                userEmployeeNos.add(planEcuMasterDataDto.getEcuOwner());
            }
            if (StringUtils.isNotBlank(planEcuMasterDataDto.getCreator())) {
                userEmployeeNos.add(planEcuMasterDataDto.getCreator());
            }
            if (StringUtils.isNotBlank(planEcuMasterDataDto.getEditor())) {
                userEmployeeNos.add(planEcuMasterDataDto.getEditor());
            }
            if (StringUtils.isNotBlank(planEcuMasterDataDto.getSwqaEngineer())) {
                userEmployeeNos.add(planEcuMasterDataDto.getSwqaEngineer());
            }
        }
        return new ArrayList<>(userEmployeeNos);
    }


    private void transferForVo(ReviewPlanEcuMasterDataDto dto, ReviewPlanEcuMasterDataResp vo,
        Map<String, CommonUserDTO> userInfoByEmployeeNos) {

        // 用户信息转换
        if (dto.getGriEcuOwner() != null) {
            vo.setGriEcuOwner(userInfoByEmployeeNos.get(dto.getGriEcuOwner()));
        }
        if (dto.getUpl() != null) {
            vo.setUpl(userInfoByEmployeeNos.get(dto.getUpl()));
        }
        if (dto.getInterfacePerson() != null) {
            vo.setInterfacePerson(userInfoByEmployeeNos.get(dto.getInterfacePerson()));
        }
        if (dto.getEcuOwner() != null) {
            vo.setEcuOwner(userInfoByEmployeeNos.get(dto.getEcuOwner()));
        }
        if (dto.getCreator() != null) {
            vo.setCreator(userInfoByEmployeeNos.get(dto.getCreator()));
        }
        if (dto.getEditor() != null) {
            vo.setEditor(userInfoByEmployeeNos.get(dto.getEditor()));
        }
        if (dto.getSwqaEngineer() != null) {
            vo.setEditor(userInfoByEmployeeNos.get(dto.getSwqaEngineer()));
        }

        // 时间信息转换
        if (dto.getCreateTime() != null) {
            vo.setCreateTime(dto.getCreateTime().getTime());
        }
        if (dto.getUpdateTime() != null) {
            vo.setUpdateTime(dto.getUpdateTime().getTime());
        }
    }

    @Override
    public void logicBatchDelete(List<Long> ids) {
        List<ReviewPlanEcuMasterDataDo> ecuMasterDataDos = reviewPlanEcuMasterDataMapper.selectBatchIds(ids);
        if (CollectionUtils.isEmpty(ecuMasterDataDos)) {
            return;
        }

        ecuMasterDataDos.forEach(curr -> {
            curr.setEditor(UserInfoContext.getUserInfo().getEmployeeNo());
            curr.setDeletedStatus(UuidUtil.getUUID());
        });
        updateBatchById(ecuMasterDataDos);
    }

    @Override
    public void restoreMasterData(List<Long> ids) {
        QueryWrapper<ReviewPlanEcuMasterDataDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("review_plan_id", ids);
        List<ReviewPlanEcuMasterDataDo> ecuMasterDataDos = reviewPlanEcuMasterDataMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(ecuMasterDataDos)) {
            return;
        }
        ecuMasterDataDos.forEach(curr -> {
            curr.setDeletedStatus(String.valueOf(DeletedStatusEnum.normal.getCode()));
            curr.setEditor(UserInfoContext.getUserInfo().getEmployeeNo());
        });
        updateBatchById(ecuMasterDataDos);
    }
}
